import datetime,json
from urllib.request import urlopen
from aliyunsdkcore.client import AcsClient
from aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest
from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest
"""
# 安装依赖
pip3 install pyyaml
pip3 install aliyun-python-sdk-core-v3
pip3 install aliyun-python-sdk-alidns==2.0.6
# 添加记录 RR_list
RR_list =  ['...','...']
"""
# 域名信息
RR_list = ['www','web']
DomainType = 'A'
region_id = "cn-shenzhen"
DomainName = 'baidu.com'
UpdateDomain = 'Auto_Lines'
# 当前时间
data_new = str(datetime.datetime.now())
# API 获取 最新IP
newip = json.load(urlopen('https://api.ipify.org/?format=json'))['ip']
# 阿里云 权限 密钥
AccessKey_ID = ''
Access_Key_Secret = '' 

for RR in RR_list:
    # 生成 阿里云 API 客户端
    def AliAccessKey(id,Secret,region):
            client = AcsClient(id, Secret, region)
            return client
    # 验证 RR 子域名 存在与否
    def GetDNSRecordId(client,DomainName):
            request = DescribeDomainRecordsRequest()
            request.set_accept_format('json')
            request.set_DomainName(DomainName)
            response = client.do_action_with_exception(request)
            json_data = json.loads(str(response, encoding='utf-8'))
            for RecordId in json_data['DomainRecords']['Record']:
                if RR == RecordId['RR']:
                    return RecordId['RecordId']
    # 更新 阿里云DNS 解析
    def UpdateDomainRecord(client,RecordId):
        try:
            request = UpdateDomainRecordRequest()
            request.set_accept_format('json')
            request.set_Value(newip)
            request.set_Type(DomainType)
            request.set_RR(RR)
            request.set_RecordId(RecordId)
            client.do_action_with_exception(request)
            print("域名:" + DomainName + " 主机:" + RR + " 记录类型:" +  DomainType + " 记录值:" +  newip)
        except Exception as e:
            print('结果：' + RR + '.infunvip.cn 解析一致 / 时间 : ' + data_new)
    # 运行 主程序
    def main():
        client = AliAccessKey(AccessKey_ID,Access_Key_Secret,region_id)
        RecordId = GetDNSRecordId(client,DomainName)
        UpdateDomainRecord(client,RecordId)
    if __name__ == "__main__":
        main()
